package com.llkj.contractmanagement.contractmanagement.contract;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.llkj.contractmanagement.main.BaseActivity;
import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.customview.ShareDialog;
import com.llkj.contractmanagement.customview.TitleBar;
import com.llkj.contractmanagement.http.HttpMethod;
import com.llkj.contractmanagement.http.UrlConfig;
import com.llkj.contractmanagement.model.ContractListBean;
import com.llkj.contractmanagement.model.UserInfoBean;
import com.llkj.contractmanagement.utils.CacheFileUtils;
import com.llkj.contractmanagement.utils.LogUtil;
import com.llkj.contractmanagement.utils.SendEmailUtils;
import com.llkj.contractmanagement.utils.ShareUtil;
import com.llkj.contractmanagement.utils.ToastUtil;
import com.mob.MobSDK;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.logging.Logger;

import butterknife.Bind;
import cn.sharesdk.framework.ShareSDK;
import okhttp3.Call;
import okhttp3.Request;
import rx.functions.Action1;

/**
 * author: dong.yj
 * created on: 2016/8/31 9:18
 * description:文件详情界面
 */
public class FileDetailsActivity extends BaseActivity implements View.OnClickListener, ShareDialog.ShareOnItemClickListener {
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_file_details;
    }

    @Bind(R.id.title_file_details)
    TitleBar titleBar;
    @Bind(R.id.tv_file_type_pdf)
    TextView tv_file_pdf;//pdf文件
    @Bind(R.id.tv_file_type_word)
    TextView tv_file_word;//word文件
    @Bind(R.id.tv_file_name)
    TextView tv_file_name;//文件名字
    @Bind(R.id.btn_open_the_file)
    Button btn_open_file;//用其他应用打开
    private ProgressDialog progressDialog;
    private ProgressDialog downloadDialog;

    private URL url;    //文件的url
    private File file;  //下载文件
    private File downloadFile;  //下载文件
    private int length; //文件长度

    private ContractListBean.HtlistBean htlistBean;
    private ShareDialog shareDialog;
    private UserInfoBean userInfoBean;
    private boolean isdownload = false;
    private boolean downloadDialogFlag = false;

    private static final String TAG = "FileDetailsActivity";

    private void requestXzzj() {
        HashMap<String, String> map = new HashMap<>();
        // user_id	1	string	用户ID
        // ht_id	1	string	合同id
        map.put("user_id", userInfoBean.getId());
        map.put("ht_id", htlistBean.getHt_id());
        HttpMethod.xzZJ(this, this, map, UrlConfig.HTTP_XZ_ZJ);
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        MobSDK.init(this);
        ShareUtil.initImagePath(this);
        init();
        setListener();
    }

    private void setListener() {
        titleBar.setTopBarClickListener(this);
        btn_open_file.setOnClickListener(this);

    }

    private void init() {
        userInfoBean = UserInfoBean.getInstance();
        htlistBean = (ContractListBean.HtlistBean) getIntent().getSerializableExtra("contractDetails");
        if (htlistBean != null) {
            if (htlistBean.getSign().equals("1")) {
                tv_file_pdf.setVisibility(View.VISIBLE);
                tv_file_word.setVisibility(View.INVISIBLE);
                tv_file_name.setText(htlistBean.getName() + ".pdf");
            } else if (htlistBean.getSign().equals("2")) {
                tv_file_pdf.setVisibility(View.INVISIBLE);
                tv_file_word.setVisibility(View.VISIBLE);
                tv_file_name.setText(htlistBean.getName() + ".doc");
            }
        }
        //实例化下载进度dialog
        downloadDialog = new ProgressDialog(FileDetailsActivity.this);
        downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        downloadDialog.setProgress(0);
        downloadDialog.setMax(100);
        downloadDialog.setCancelable(false);

        requestAddHtZj();
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if(aBoolean){
                            downFile();
                        }
                    }
                });
    }

    private void requestAddHtZj() {
        HashMap<String, String> map = new HashMap<>();
        // user_id	1	string	用户ID
        // ht_id	1	string	合同id
        map.put("user_id", userInfoBean.getId());
        map.put("ht_id", htlistBean.getHt_id());
        HttpMethod.htZj(this, this, map, UrlConfig.HTTP_HT_ZJ);
    }

    /*
    * 进入页面，默认下载文件
    * */
    private void downFile() {
        isdownload = false;
        CacheFileUtils.getInstance(this);
        file = new File(CacheFileUtils.FOLDER_MAIN, getFileName(htlistBean));

        OkHttpUtils.get()
                .url(htlistBean.getUrl())
                .build()
                .execute(new FileCallBack(CacheFileUtils.FOLDER_MAIN, getFileName(htlistBean)) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(File response) {
                        isdownload = true;
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void inProgress(float progress, long total) {

                    }

                });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_open_the_file:
                if (!isdownload) {
                    if (progressDialog == null) {
                        progressDialog = new ProgressDialog(this);
                        progressDialog.setMessage("正在加载");
                        progressDialog.setCancelable(false);
                    }
                    progressDialog.show();
                } else {
                    if (htlistBean.getSign().equals("1")) {
                        openPdf();
                    } else {
                        openWord();
                    }
                }
                break;
        }
    }

    /*
    * 打开word文件
    * */
    private void openWord() {
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/msword");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtil.makeShortText(this, "No Application Available to View WORD");
        }
    }

    /*
    * 打开pdf文件
    * */
    private void openPdf() {
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtil.makeShortText(this, "No Application Available to View PDF");
        }
    }

    private String getFileName(ContractListBean.HtlistBean htlistBean) {
//        int index = url.lastIndexOf("/") + 1;
        if (htlistBean.getSign().equals("1")) {
            return htlistBean.getName() + ".pdf";
        } else {
            return htlistBean.getName() + ".doc";
        }
    }

    @Override
    public void down() {
        shareDialog.dismiss();
        downloadFile = new File(CacheFileUtils.FOLDER_CACHE, getFileName(htlistBean));
        if (downloadFile.exists()) {
            ToastUtil.makeShortText(this, "您已下载");
        } else {
            downloadDialog.show();
            getFile(CacheFileUtils.FOLDER_CACHE, getFileName(htlistBean));
        }
    }

    private void getFile(String folderCache, String fileName) {
        OkHttpUtils.get()
                .url(htlistBean.getUrl())
                .build()
                .execute(new FileCallBack(folderCache, fileName) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(File response) {
                        downloadDialogFlag = true;
                        if (downloadDialog.isShowing()) {
                            downloadDialog.dismiss();
                        }
                        requestXzzj();
                    }

                    @Override
                    public void inProgress(float progress, long total) {
                        downloadDialog.setProgress((int) (100 * progress));
                        Log.e(TAG, "inProgress :" + (int) (100 * progress));
                    }

                });
    }

    @Override
    public void shareQQ() {
        ShareUtil.shareQQ(htlistBean.getName(), htlistBean.getName(), htlistBean.getUrl(), "");
        shareDialog.dismiss();
    }

    @Override
    public void shareWeChat() {
        ShareUtil.shareWeiXin(htlistBean.getName(), htlistBean.getName(), htlistBean.getUrl(), "");
        shareDialog.dismiss();
    }

    @Override
    public void email() {
        SendEmailUtils.getInstance().sendEmail(this);
        shareDialog.dismiss();
    }

    @Override
    public void leftClick() {
        super.leftClick();
        File delFile = new File(CacheFileUtils.FOLDER_MAIN, getFileName(htlistBean));
        if (delFile.exists()) {
            delFile.delete();
        }
    }

    @Override
    public void rightClick() {
        super.rightClick();
        if (shareDialog == null) {
            shareDialog = new ShareDialog(this);
            shareDialog.setShareOnItemClickListener(this);
        }
        shareDialog.show();

    }

    @Override
    public void onSuccessHttp(String responseInfo, int resultCode) {
        super.onSuccessHttp(responseInfo, resultCode);
        switch (resultCode) {
            case UrlConfig.HTTP_HT_ZJ:

                break;
            case UrlConfig.HTTP_XZ_ZJ:
                ToastUtil.makeShortText(FileDetailsActivity.this, "下载完成");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        File delFile = new File(CacheFileUtils.FOLDER_MAIN, getFileName(htlistBean));
        if (delFile.exists()) {
            delFile.delete();
        }
    }

}
